package com.example.yskjproject.ui.activity;


import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import com.example.yskjproject.base.BaseActivity;
import com.example.yskjproject.content.EventContent;
import com.example.yskjproject.databinding.ActivityNickNameAlertBinding;
import com.example.yskjproject.event.EventMessage;
import com.example.yskjproject.http.Urls;
import com.example.yskjproject.http.callback.JsonCallback;
import com.example.yskjproject.model.LzyResponse;
import com.example.yskjproject.utils.EventBusUtil;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.tencent.qcloud.tuicore.util.ToastUtil;

import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;

public class NickNameActivity extends BaseActivity<ActivityNickNameAlertBinding> {
    private ActivityNickNameAlertBinding mNickNameBinding;
    private Gson gson;

    @Override
    protected ActivityNickNameAlertBinding getViewBinding() {
        mNickNameBinding = ActivityNickNameAlertBinding.inflate(LayoutInflater.from(this));
        return mNickNameBinding;
    }

    @Override
    protected boolean shouldShowTitle() {
        return false;
    }

    @Override
    protected void initData() {
        mNickNameBinding.tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mNickNameBinding.tvSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(mNickNameBinding.etNickName.getText())) {
                    gson = new Gson();
                    saveNickName();
                }
            }
        });

    }

    private void saveNickName() {
        Map<String, Object> jsonParams = new HashMap<>();
        jsonParams.put("nick_name", mNickNameBinding.etNickName.getText().toString());
        String paramsDate = gson.toJson(jsonParams);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), paramsDate);
        OkGo.<LzyResponse<Void>>post(Urls.UPDATE_USER).upRequestBody(requestBody).execute(new JsonCallback<LzyResponse<Void>>() {
            @Override
            public void onSuccess(Response<LzyResponse<Void>> response) {
                ToastUtil.toastLongMessage("昵称修改成功");
                EventMessage eventMessage = new EventMessage(EventContent.update_nick_name, mNickNameBinding.etNickName.getText().toString());
                EventBusUtil.sendEvent(eventMessage);
                finish();
            }

            @Override
            public void onError(Response<LzyResponse<Void>> response) {
                super.onError(response);
            }
        });
    }
}
